package com.foreveross.proxyip.core.pools.validate.handtailor;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;

import com.foreveross.proxyip.core.pools.validate.AbsHandtailorValidate;
import com.foreveross.proxyip.entity.ProxyIpBean;


public class AirChinaValidate extends  AbsHandtailorValidate {


	private static final String REQUEST_HOST = "et.airchina.com.cn";// 主机
	private static final String REQUEST_PATH = "/InternetBooking/AirLowFareSearchExternal.do";// 路径
	
	private HttpClient httpClient;
	@Override
	public boolean proxyConnect(ProxyIpBean proxyIp,HttpParams httpParams) throws Exception {
//		Date gradDate = DateUtils.parseDate(taskQueue.getFlightDate(), "yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());

		HttpUriRequest request = null;
		//String cookie="JSESSIONID=2E79EA48FDFC89EA354FDF0625C67116; current_PoS=AIRCHINA_CN; BIGipServerWeb_http=4228062892.20480.0000; s_sess=%20s_cc%3Dtrue%3B%20s_sq%3D%3B; currentLang=zh_CN; mbox=session#1355925804659-307507#1355927871|check#true#1355926071";
		try {
			httpClient = super.getHttpClient(proxyIp, httpParams); 
			httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
					CookiePolicy.BEST_MATCH);
			request = new HttpGet(getConnectUrl());
			httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
					CookiePolicy.BEST_MATCH);
			this.setRequest(request);
			request.setHeader("Cookie",
					getCookies(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DATE), "广州","北京"));//taskQueue.getFromCity(), taskQueue.getToCity()
			HttpResponse response = httpClient.execute(request);
			String statu = response.getStatusLine().toString();
			if (statu != null && statu.indexOf("200") != -1) {
				return true;
			}
			return false;
		}finally{
			if(request != null) request.abort();
			request = null;

		}
	}
	
	@Override
	public HttpParams getHttpParams() {
		HttpParams httpParams = new BasicHttpParams();
		httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
		httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
		return httpParams;
	}
	
	private URI produceUri(int year, int month, int day,
			String depPort, String arrPort) throws URISyntaxException {

		// 请求参数
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("tripType", "OW"));
		qparams.add(new BasicNameValuePair("searchType", "FARE"));
		qparams.add(new BasicNameValuePair("flexibleSearch", "false"));
		qparams.add(new BasicNameValuePair("directFlightsOnly", "false"));
		qparams.add(new BasicNameValuePair("fareOptions", "1.FAR.X"));
		qparams.add(new BasicNameValuePair("outboundOption.originLocationCode",
				depPort));
		qparams.add(new BasicNameValuePair(
				"outboundOption.destinationLocationCode", arrPort));
		qparams.add(new BasicNameValuePair("outboundOption.departureDay", day+""));
		qparams.add(new BasicNameValuePair("outboundOption.departureMonth",
				month+""));
		qparams.add(new BasicNameValuePair("outboundOption.departureYear", year+""));
		qparams.add(new BasicNameValuePair("outboundOption.departureTime", "NA"));
		qparams.add(new BasicNameValuePair("guestTypes[0].type", "ADT"));
		qparams.add(new BasicNameValuePair("guestTypes[0].amount", "1"));
		qparams.add(new BasicNameValuePair("guestTypes[1].type", "CNN"));
		qparams.add(new BasicNameValuePair("guestTypes[1].amount", "0"));
		qparams.add(new BasicNameValuePair("pos", "AIRCHINA_CN"));
		qparams.add(new BasicNameValuePair("lang", "zh_CN"));
		qparams.add(new BasicNameValuePair("guestTypes[2].type", "INF"));
		qparams.add(new BasicNameValuePair("guestTypes[2].amount", "0"));

		return URIUtils.createURI("http", REQUEST_HOST, -1,
					REQUEST_PATH, URLEncodedUtils.format(qparams, "UTF-8"),
					null);
	}

	private String getCookies(int year,
			int month, int day, String depPort, String arrPort) throws Exception
			 {
		String cookie = "";
		HttpUriRequest request = new HttpPost(produceUri(year, month, day, depPort,
				arrPort));

		setRequest(request);
		
		request.setHeader(
				"Cookie",
				"current_PoS=AIRCHINA_CN; currentLang=zh_CN");
		try {
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
			HttpResponse response = httpClient.execute(request, new BasicHttpContext());
			
			HeaderElementIterator it = new BasicHeaderElementIterator(
					response.headerIterator("Set-Cookie"));
			while (it.hasNext()) {
				HeaderElement elem = it.nextElement();
				if (elem != null && elem.getName().equals("JSESSIONID")) {
					cookie += elem.getName() + "=" + elem.getValue();
				}
				if (elem != null
						&& elem.getName().equals("BIGipServerWeb_http")) {
					cookie += "; " + elem.getName() + "=" + elem.getValue();
				}
			}


		}finally {
			if(request != null){ 
				 request.abort();
				}
		}
		return cookie;
	}

	private void setRequest(HttpUriRequest request) {
		request.setHeader("Accept",
				"Accept	text/html, application/xhtml+xml, */*");
		request.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
		request.setHeader("Accept-Language", "zh-CN");
		request.setHeader("Connection", "keep-Alive");
		request.setHeader("Host", "et.airchina.com.cn");
		request.setHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19");
	}



	private String getConnectUrl() {
		return "http://et.airchina.com.cn/InternetBooking/AirLowFareSearchExt.do";
	}

	
	

}
